﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Linq.Expressions;

namespace CH.Study.ConsoleApp.ExpressionTree
{
    /// <summary>
    /// 可查询器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class QueryQueryable<T> : IQueryable<T>, IOrderedQueryable<T>
    {
        public QueryQueryable(IQueryProvider provider)
        {
            this.Provider = provider;
            this.Expression = Expression.Constant(this);
        }
        public QueryQueryable(IQueryProvider provider, Expression expression)
        {
            this.Provider = provider;
            this.Expression = expression;
        }

        public IEnumerator<T> GetEnumerator()
        {
            this.Expression = new SelectExpression(this.Expression);
            return (Provider.Execute<IEnumerable<T>>(this.Expression)).GetEnumerator();
        }

        public PageEntity GetPageEntity()
        {

            SelectExpression se = this.Expression as SelectExpression;
            if (se != null)
            {
                return new PageEntity() { Index = se.PageIndex, Size = se.PageSize, TotalRecord = se.TotalRecord };
            }
            else
            {
                return new PageEntity() { Index = 0, Size = 0, TotalRecord = 0 };
            }
        }


        public int Add(object obj)
        {
            this.Expression = new InsertExpression(obj);
            return Provider.Execute<int>(this.Expression);
        }

        public int Delete(Expression<Func<T, bool>> expression)
        {

            this.Expression = new DeleteExpression(typeof(T), expression);
            return Provider.Execute<int>(this.Expression);
        }
        public int Update(object obj, Expression<Func<T, bool>> expression)
        {
            this.Expression = new UpdateExpression(obj, expression);
            return Provider.Execute<int>(this.Expression);
        }


        IEnumerator IEnumerable.GetEnumerator()
        {
            this.Expression = new SelectExpression(this.Expression);
            return (Provider.Execute<IEnumerable>(this.Expression)).GetEnumerator();
        }

        public Type ElementType
        {
            get { return typeof(T); }
        }
        /// <summary>
        /// 查询表达式树
        /// </summary>
        public Expression Expression
        {
            get;
            private set;
        }
        /// <summary>
        /// 数据提供集
        /// </summary>
        public IQueryProvider Provider
        {

            get;
            private set;
        }
    }
}
